package com.iflytek.ossp.auth.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class HomeController {

	@Resource
	private Producer captchaProducer;

	@RequestMapping(value = "/")
	public String index() {
		return "auth/index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "auth/login";
	}

	@RequestMapping(value = "/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:/";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(HttpServletRequest request,
			HttpServletResponse response, String loginName, String password,
			String captchaCode) {
		request.setAttribute("loginName", loginName);

		if (StringUtils.isEmpty(loginName)) {
			request.setAttribute("message", "用户名不能为空");
			return "auth/login";
		}
		if (StringUtils.isEmpty(password)) {
			request.setAttribute("message", "密码不能为空");
			return "auth/login";
		}
		if (StringUtils.isEmpty(captchaCode)) {
			request.setAttribute("message", "验证码不能为空");
			return "auth/login";
		}
		String captcha = (String) request.getSession().getAttribute(
				Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isEmpty(captcha)
				|| !captcha.equalsIgnoreCase(captchaCode)) {
			request.setAttribute("message", "验证码有误,请重试");
			return "auth/login";
		}

		String encodePwd = DigestUtils.md5DigestAsHex(password.getBytes());
		UsernamePasswordToken token = new UsernamePasswordToken(loginName,
				encodePwd, true);
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			request.setAttribute("message", "用户名或密码错误");
			return "auth/login";
		}
		if (SecurityUtils.getSubject().isAuthenticated()) {
			String fallbackUrl = "redirect:/";
			try {
				// redirect to previously requested page
				WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
			} catch (IOException e) {
				return fallbackUrl;
			}
			// return null to prevent spring render another page
			return null;
		}
		return "auth/login";
	}

	@RequestMapping(value = "/captcha-image")
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");

		String capText = captchaProducer.createText();
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
				capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}
}
